package com.innovation.chengzhangriji.ui.widget;

import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import com.innovation.chengzhangriji.R;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

public class ThemesAdapter extends RecyclerView.Adapter<ThemeViewHolder> implements ThemeViewHolder.OnSelectListener {

    private ArrayList<Theme> themeArrayList;

    private int mPosition = -1;

    public ThemesAdapter() {
        themeArrayList = new ArrayList<Theme>();
    }

    @Override
    public ThemeViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_theme, parent, false);
        ThemeViewHolder viewHolder = new ThemeViewHolder(view);
        viewHolder.setOnSelectListener(this);
        return viewHolder;
    }

    @Override
    public void onBindViewHolder(ThemeViewHolder holder, int position) {
        holder.setText(themeArrayList.get(position).getTheme());
        holder.setChange(themeArrayList.get(position).isSelect());
    }

    @Override
    public int getItemCount() {
        if (themeArrayList != null) {
            return themeArrayList.size();
        }
        return 0;
    }

    @Override
    public void onSelect(ThemeViewHolder holder) {
        if (mPosition != holder.getLayoutPosition()) {
            mPosition = holder.getLayoutPosition();
            for (Theme theme : themeArrayList) {
                theme.setSelect(false);
            }
            themeArrayList.get(mPosition).setSelect(true);
            notifyDataSetChanged();
        } else {
            themeArrayList.get(mPosition).setSelect(false);
            notifyDataSetChanged();
            mPosition = -1;
        }
    }

    /**
     * 增加主题
     */
    public void addThemes(String[] texts) {
        int length = texts.length;
        Theme[] themes = new Theme[length];
        for (int i = 0; i < length; i++) {
            themes[i] = new Theme();
            themes[i].setTheme(texts[i]);
        }
        List<Theme> list = Arrays.asList(themes);
        themeArrayList.addAll(list);
        notifyDataSetChanged();
    }

    /**
     * 获得主题
     */
    public String getTheme() {
        if (mPosition == -1) {
            return null;
        }
        return themeArrayList.get(mPosition).getTheme();
    }

    private class Theme {

        private boolean isSelect;

        private String theme;

        public boolean isSelect() {
            return isSelect;
        }

        public void setSelect(boolean isSelect) {
            this.isSelect = isSelect;
        }

        public String getTheme() {
            return theme;
        }

        public void setTheme(String theme) {
            this.theme = theme;
        }
    }
}
